package utils

import (
	"alertmanagerWebhook/global"
	"fmt"
	"net/smtp"
)

func SendEmail(subject, body string) error {
	global.Logger.Debugf("准备SMTP认证，发件人: %s", global.Config.Email.Smtp_from)
	auth := smtp.PlainAuth("", global.Config.Email.Smtp_from, global.Config.Email.Smtp_password, global.Config.Email.Smtp_Host)

	to := []string{global.Config.Email.Smtp_to}
	global.Logger.Debugf("设置邮件收件人: %s", to[0])

	msg := []byte(fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",
		global.Config.Email.Smtp_from,
		global.Config.Email.Smtp_to,
		subject,
		body))

	smtpAddr := fmt.Sprintf("%s:%d", global.Config.Email.Smtp_Host, global.Config.Email.Smtp_port)
	global.Logger.Debugf("连接SMTP服务器: %s", smtpAddr)

	err := smtp.SendMail(smtpAddr, auth, global.Config.Email.Smtp_from, to, msg)
	if err != nil {
		global.Logger.Errorf("SMTP发送失败: %v", err)
	}
	return err
}
